//
//  DetailCommunityViewController.m
//  shusheng
//
//  Created by rimi on 16/7/15.
//  Copyright © 2016年 yuying. All rights reserved.
//

#import "DetailCommunityViewController.h"
#import "DCheadView.h"
#import "DetailCommunityCell.h"
#import "SDAutoLayout.h"

@interface DetailCommunityViewController ()<UITableViewDataSource,UITableViewDelegate>
{
     NSMutableArray *dataSource;
   
    NSMutableArray *commentArray; // 评论、回复数据
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) AVIMClient *client;





- (void)initializeUserInterface;


@end

@implementation DetailCommunityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillAppear:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillHidden:) name:UIKeyboardWillHideNotification object:nil];
    
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,80, 45)];
    [backButton setTitle:@"<返回" forState:UIControlStateNormal];
    [backButton setTitleColor:FONT_COLOR forState:UIControlStateNormal];
    
    [backButton addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    backButton.center = CGPointMake( 120, 32);
    [self.view addSubview:backButton];
    [backButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(BUTTON_HEIGHT);
        make.left.equalTo(self.view).with.offset(10);
        make.width.offset(50);
        make.height.offset(30);
    }];
    
    UIButton *commentButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0,80, 45)];
    [commentButton setTitleColor:FONT_COLOR forState:UIControlStateNormal];
    commentButton.center = CGPointMake( SCREEN_WIDTH - 80, 32);
    [commentButton setBackgroundImage:[UIImage imageNamed:@"评论 (1).png"] forState:UIControlStateNormal];
    [commentButton addTarget:self action:@selector(goCommentButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:commentButton];
    [commentButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).with.offset(BUTTON_HEIGHT);
        make.right.equalTo(self.view).with.offset(-30);
        make.width.offset(35);
        make.height.offset(25);
    }];
    
    dataSource = [[NSMutableArray alloc] init];
    if (self.currentObject[@"dataSource"] != nil) {
         [dataSource addObjectsFromArray:self.currentObject[@"dataSource"]];
    }
   
    commentArray = [[NSMutableArray alloc] init];
    

    [self initializeUserInterface];
    


}


- (void)dealloc {
    // 移除通知
    // ARC模式下无需调用[super dealloc];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark -- 键盘处理
// 键盘处理
- (void)keyBoardWillAppear:(NSNotification *)notification {
    self.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds) - 200);
}

// 键盘处理
- (void)keyBoardWillHidden:(NSNotification *)notification {
    self.view.center = CGPointMake(CGRectGetMidX(self.view.bounds), [UIScreen mainScreen].bounds.size.height / 2);
}

#pragma mark *** Touches methods ***
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    // 收起键盘
    [self.view endEditing:YES];
}



- (void)initializeUserInterface{
   
    
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
         make.top.equalTo(self.view).with.offset(64);
         make.left.equalTo(self.view).with.offset(0);
         make.right.equalTo(self.view).with.offset(0);
         make.bottom.equalTo(self.view).with.offset(0);
        
    }];
    

    [self.view addSubview:self.bottomView];
    [self.bottomView addSubview:self.textField];
    [self.textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomView.mas_top).with.offset(0);
        make.bottom.mas_equalTo(self.bottomView.mas_bottom).with.offset(0);
        make.left.mas_equalTo(self.bottomView.mas_left).with.offset(0);
        make.right.mas_equalTo(self.bottomView.mas_right).with.offset(-50);
        
    }];
    
    [self.bottomView addSubview:self.sendButton];
    [self.sendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.bottomView.mas_top).with.offset(0);
        make.right.mas_equalTo(self.bottomView.mas_right).with.offset(0);
        make.bottom.mas_equalTo(self.bottomView.mas_bottom).with.offset(0);
        make.left.mas_equalTo(self.textField.mas_right).with.offset(0);
    }];
    
    
    
    
}

- (void)goCommentButton:(UIButton *)sender {
    self.bottomView.hidden = NO;
    self.sendButton.tag = 100;
    self.textField.text = @"";
    NSLog(@"评论");
    

}

#pragma mark -- UITableViewDataSource && UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
     DCheadView *head = [[DCheadView alloc] initWithReuseIdentifier:@"DCheadView"];
//    UIView *head = [tableView dequeueReusableCellWithIdentifier:@"DCheadView"];
//    
//    if (!head) {
//        head = [[DCheadView alloc]initWithReuseIdentifier:@"DCheadView"];
//    }
    
    

    
    head.titleLabel.text = self.headSource[@"title"];
    head.detailLabel.text = self.headSource[@"content"];
    
    NSDate* str = self.headSource[@"createdAt"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM-dd HH:mm"];
    NSString *dateString = [dateFormatter stringFromDate:str];
    NSString *objectid = self.headSource[@"author"][@"objectId"];
    AVQuery *query = [AVQuery queryWithClassName:@"_User"];
    [query getObjectInBackgroundWithId:objectid block:^(AVObject *object, NSError *error) {
        //       cell.authorName.text = object[@"username"];
//        head.nameLabel.text = [object[@"username"] stringByAppendingString:@"  "];
//        head.nameLabel.text = [head.nameLabel.text stringByAppendingString:dateString];
        head.nameLabel.text = object[@"username"];
        
        
    }];
    [head.nameImageView setImage:[UIImage imageNamed:@"头像.png"]];
    head.timeLabel.text = [@"1楼 " stringByAppendingString:dateString];
    
    
    
    
    
    return head;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
     return [self cellHeightForIndexPath:indexPath cellContentViewWidth:[UIScreen mainScreen].bounds.size.width tableView:tableView];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 150;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DetailCommunityCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DetailCommunityCell"];
    
    if (!cell) {
        cell = [[DetailCommunityCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"DetailCommunityCell"];
        cell.detailVc = self;
        
    }
   
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    
//    @property (nonatomic,strong) UIImageView *headImageView; // 头像
//    @property (nonatomic,strong) UILabel *nameLbael; // 名字
//    @property (nonatomic,strong) UILabel *contenLabel; // 内容
//    @property (nonatomic,strong) UILabel *timeLabel; // 时间、日期、楼数
//    @property (nonatomic,strong) UIButton *replyButton;// 回复按钮
//    NSLog(@"%@",dataSource);
    cell.nameLbael.text = dataSource[indexPath.row][@"user"];
    cell.contenLabel.text = dataSource[indexPath.row][@"content"];
    NSInteger lou = indexPath.row +2;
    NSString *timestring = dataSource[indexPath.row][@"currentTime"];
    NSString *newStr = [timestring substringWithRange:NSMakeRange(5, 11)];
    NSString *newString = [NSString stringWithFormat:@"%ld楼  %@",(long)lou,newStr];
    cell.timeLabel.text = newString;
    cell.replyButton.tag = indexPath.row + 101;
    cell.data = dataSource[indexPath.row][@"commentArray"];
    if (cell.data.count == 0) {
        cell.pinlunView.hidden = YES;
    }else {
        cell.pinlunView.hidden = NO;
    }
    NSString *imageName = [NSString stringWithFormat:@"头像.png"];
    UIImage *image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForAuxiliaryExecutable:imageName]];
    
    cell.headImageView.image = image;
    NSLog(@"%@",cell.data);
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

}




#pragma mark -- Getters

- (NSString *)secondUser{
    if (!_secondUser) {
        _secondUser = @"";
       
        
    }
    return _secondUser;
}

- (UIView *)bottomView{
    if (!_bottomView) {
        _bottomView= [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-40, SCREEN_WIDTH, 40)];
        _bottomView.hidden = YES;
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
//        _tableView.style = UITableViewStyleGrouped
     
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }
    return _tableView;
}


- (void)backButton:sender{
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}


- (UITextField *)textField{
    if (!_textField) {
        _textField = [[UITextField alloc] init];
        _textField.borderStyle = UITextBorderStyleLine;
    }
    return _textField;
}


- (UIButton *)sendButton{
    if (!_sendButton) {
        _sendButton = [[UIButton alloc] init];
        [_sendButton setImage:[UIImage imageNamed:@"发送.png"] forState:UIControlStateNormal];
        [_sendButton addTarget:self action:@selector(respondsToSendButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendButton;
}

- (void)respondsToSendButton:(UIButton *)sender{
    if (sender.tag == 100) {
        NSString *timeStr = [ToolOfBasic nowTime];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:[AVUser currentUser].username forKey:@"user"];
        [dic setObject:self.textField.text forKey:@"content"];
        [dic setObject:timeStr forKey:@"currentTime"];
        
        [dataSource addObject:dic];
        
        //    [self.currentObject addUniqueObjectsFromArray:dataSource forKey:@"dataSource"];
        //    [self.currentObject saveInBackground];
        //    NSLog(@"%@",dataSource);
        [self.currentObject setObject:dataSource forKey:@"dataSource"];// 设置名称
        [self.currentObject saveInBackground];// 保存到云端
        self.textField.text = @"";
        self.bottomView.hidden = YES;
        [self.tableView reloadData];
    }else if (sender.tag > 100){
        if (dataSource[sender.tag -101][@"commentArray"] != nil) {
//            [commentArray removeAllObjects];
            commentArray = [[NSMutableArray alloc] initWithArray:dataSource[sender.tag -101][@"commentArray"] ];
//            commentArray = dataSource[sender.tag -101][@"commentArray"];
        }
        NSMutableDictionary *oldDic = [[NSMutableDictionary alloc] initWithDictionary:dataSource[sender.tag -101]];
        
         NSString *timeStr = [ToolOfBasic nowTime];
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        [dic setObject:[AVUser currentUser].username forKey:@"commentUser"];
        [dic setObject:self.textField.text forKey:@"commentData"];
        [dic setObject:timeStr forKey:@"currentTimes"];
        [dic setObject:self.secondUser forKey:@"secondUser"];
        [commentArray addObject:dic];
        
        [oldDic setObject:commentArray forKey:@"commentArray"];
        
        [dataSource removeObjectAtIndex:sender.tag - 101];
        [dataSource insertObject:oldDic atIndex:sender.tag - 101];
        [self.currentObject setObject:dataSource forKey:@"dataSource"];// 设置名称
        [self.currentObject saveInBackground];// 保存到云端
        self.secondUser = @"";
        self.textField.text = @"";
        self.bottomView.hidden = YES;
        [self.tableView reloadData];
        NSLog(@"%ld",(long)sender.tag);
    }
    
    
    
}

@end
